<?php

namespace App\Http\Controllers\api\base;

use App\Api\ExpressPrintService;
use App\Api\PrinterService;
use App\Api\PrintService;
use App\Config\YlyConfig;
use App\Http\Requests\base\DecodeRequest;
use App\Http\Requests\banner\BannerRequest;
use App\Http\Requests\base\PhoneRequest;
use App\Jobs\goods\PrintTicket;
use App\Models\config\Config;
use App\Models\goods\GoodsCate;
use App\Models\goods\Order;
use App\Models\User;
use App\Http\Controllers\Controller;
use App\Models\user\MoneyDetail;
use App\Oauth\YlyOauthClient;
use App\Services\banner\BannerService;
use App\Services\common\SmsService;
use Carbon\Carbon;
use EasyWeChat\Factory;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Storage;

class IndexController extends Controller
{
    //




    public function index()
    {
        $data = request()->input();
        dd($data['id']);

        $data =  User::cache(60)->where('id','!=',0)->select('id','name')->paginate(2);

        return success($data,'获取成功');


//        $data = Cache::remember('xiaosong',60,function (){
//            return 'xxxxxxxx';
//        });
//
//        dd($data);
//
//        dd(\request()->input());
//
//        (new User())->where('id',1)->first()->cache();
//        User::where('id',1)->first()->cache();
    }

    /**
     * app基础配置获取
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     */
    public function appBasic(Request $request)
    {

        if(empty($request->keywords)){
            return error('关键字不能为空');
        };

        $rows = Config::getConfig($request->keywords);
        return success($rows);

    }


    /**
     * 发送短信
     * @param PhoneRequest $request
     * @param SmsService $service
     * @return mixed
     */
    public function sms(PhoneRequest $request,SmsService $service)
    {

        if ($service->sendSms($request->phone)){
            return successWithMsg('发送成功');
        };
        return error('发送失败');
    }

    /**
     * 轮播图获取
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     */
    public function getBanner(BannerRequest $request,BannerService $service)
    {
        return success($service->getBanner($request->cid,$request->num??Config::getConfig('banner_num')));
    }

    /**
     *  打印小票
     */
    public function printTicket()
    {

        $order = Order::latest()->where('status','>=',1)->first();
//        PrintTicket::dispatch($order);
        PrintTicket::dispatch($order);
        dd('xxx');
//        dd(\config('yly'));

        $order = Order::latest()->where('status','>=',1)->first();
        $config = new YlyConfig(\config('yly.clientId'), \config('yly.clientSecret'));

        if (Cache::has('ylyToken')) {
            $token = Cache::get('ylyToken');
        } else {
            $client = new YlyOauthClient($config);
            $token = $client->getToken();   //若是开放型应用请传授权码code
            Cache::put('ylyToken', $token, Carbon::now()->addDay());
        }

        $access_token = $token->access_token;
//        $printer = new PrinterService($token->access_token, $config);
//
//        $data = $printer->addPrinter(\config('yly.machineCode'), \config('yly.mSign'));
//            dd($config,$data);
        $print = new PrintService($token->access_token, $config);
        $expressPrint = new ExpressPrintService($access_token, $config);
        $content = array(
            "OrderCode"=> "0126578665784971",
            "ShipperCode"=> "SF",  //SF YZPY  HTKY  YD
            "PayType"=> 1,
            "ExpType"=> 1,
            "Cost"=>6.0,
            "OtherCost"=> 7.0,
            "CustomerName" => '1264546',
            "CustomerPwd" => '4545454',
            "MonthCode" => '',
            "Sender"=> array(
                "Company" => "5645645",
                "Name" => "Taylor",
                "Mobile" => "15018442396",
                "ProvinceName" => "上海",
                "CityName" => "上海",
                "PostCode" => '61000',
                "ExpAreaName" => "青浦区",
                "Address" => "明珠路73号"
            ),
            "Receiver"=> array(
                "Company"=> "789789",
                "Name"=> "Yann",
                "Mobile"=> "15018442396",
                "ProvinceName"=> "北京",
                "CityName"=> "北京",
                "PostCode" => '61000',
                "ExpAreaName"=> "朝阳区",
                "Address"=> "三里屯街道雅秀大厦"
            ),
            "Commodity" => array(
                array(
                    "GoodsName"=> "鞋子",
                )
            ),
            "AddService"=> array(
                array(
                    "Name"=> "COD",
                    "Value"=> "1020",
                    "CustomerID" => "44564"
                )
            ),
            "StartDate" => date("y-M-d H:i:s",time() + 7200),
            "Weight"=> 1.0,
            "Quantity"=> 1,
            "Volume"=> 0.0,
            "Remark"=> "小心轻放",
        );



        var_dump($expressPrint->index(config('yly.YlyMachineCode'), $content, $order->id));

    }


    /**
     * 测试接口  预留
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     */
    public function test(Request $request,SmsService $service)
    {



        $str = "{
    \"code\": 200,
    \"message\": \"请求成功\",
    \"data\": [
        {
            \"id\": 11,
            \"pid\": 0,
            \"icon\": \"http://file2.qishengmeiyi.com/images/timgC8YV4QUO.jpg\",
            \"name\": \"文具区\",
            \"subs\": [
                {
                    \"id\": 35,
                    \"pid\": 11,
                    \"icon\": \"http://file2.qishengmeiyi.com/images/2f1357fe97ad11b63d17ab831ba199a9.jpg\",
                    \"name\": \"文具区二级分类1\",
                    \"subs\": [
                        {
                            \"id\": 13,
                            \"icon\": \"http://file2.qishengmeiyi.com/images/timgP7E8QFHF.jpg\",
                            \"name\": \"文具区三级分类11\",
                            \"pid\": 35
                        },
                        {
                            \"id\": 31,
                            \"icon\": \"http://file2.qishengmeiyi.com/images/微信图片_20200605214702.jpg\",
                            \"name\": \"文具区三级分类12\",
                            \"pid\": 35
                        }
                    ]
                },
                {
                    \"id\": 12,
                    \"pid\": 11,
                    \"icon\": \"http://file2.qishengmeiyi.com/images/timgX176899N.jpg\",
                    \"name\": \"文具区二级分类2\",
                    \"subs\": [
                        {
                            \"id\": 34,
                            \"icon\": \"http://file2.qishengmeiyi.com/images/4ea04502a4a16cf858a653b6665c5cb6.jpg\",
                            \"name\": \"文具区三级分类21\",
                            \"pid\": 12
                        },
                        {
                            \"id\": 33,
                            \"icon\": \"http://file2.qishengmeiyi.com/images/a78b5646bea094b2ff7fce1913db9336.jpg\",
                            \"name\": \"文具区三级分类22\",
                            \"pid\": 12
                        }
                    ]
                }
            ]
        },
        {
            \"id\": 9,
            \"pid\": 0,
            \"icon\": \"http://file2.qishengmeiyi.com/images/9b165f19514aaddfd1c57c730a7823e0.jpg\",
            \"name\": \"玩具区\",
            \"subs\": [
                {
                    \"id\": 30,
                    \"pid\": 9,
                    \"icon\": \"http://file2.qishengmeiyi.com/images/微信图片_20200611165823.jpg\",
                    \"name\": \"玩具二级分类1\",
                    \"subs\": [
                        {
                            \"id\": 28,
                            \"icon\": \"http://file2.qishengmeiyi.com/images/我.jpg\",
                            \"name\": \"玩具三级分类1\",
                            \"pid\": 30
                        }
                    ]
                },
                {
                    \"id\": 29,
                    \"pid\": 9,
                    \"icon\": \"http://file2.qishengmeiyi.com/images/微信图片_20200611165522.jpg\",
                    \"name\": \"玩具二级分类2\",
                    \"subs\": [
                        {
                            \"id\": 27,
                            \"icon\": \"http://file2.qishengmeiyi.com/images/微信图片_20200611165112.jpg\",
                            \"name\": \"玩具三级分类2\",
                            \"pid\": 29
                        }
                    ]
                }
            ]
        },
        {
            \"id\": 32,
            \"pid\": 0,
            \"icon\": \"http://file2.qishengmeiyi.com/images/295643d0b930b15adc9f0313087bf475.jpg\",
            \"name\": \"新品区\",
            \"subs\": [
                {
                    \"id\": 17,
                    \"pid\": 32,
                    \"icon\": \"http://file2.qishengmeiyi.com/images/微信图片_20200605214031.jpg\",
                    \"name\": \"新品区二级分类\",
                    \"subs\": [
                        {
                            \"id\": 24,
                            \"icon\": \"http://file2.qishengmeiyi.com/images/微信图片_20200605213957.jpg\",
                            \"name\": \"新平区三级分类\",
                            \"pid\": 17
                        }
                    ]
                }
            ]
        }
    ]
}";
        $arr = json_decode($str,true)['data'];

        $rows = [];

        foreach ($arr as $value){
            $rows[] = [
                'id' => $value['id'],
                'pid' => $value['pid'],
                'icon' => $value['icon'],
                'name' => $value['name'],
                'created_at' => Carbon::now(),
                'updated_at' => Carbon::now(),
            ];
            foreach ($value['subs'] as $sub){
                $rows[] = [
                    'id' => $sub['id'],
                    'pid' => $sub['pid'],
                    'icon' => $sub['icon'],
                    'name' => $sub['name'],
                    'created_at' => Carbon::now(),
                    'updated_at' => Carbon::now(),
                ];
                foreach ($sub['subs'] as $sub1){
                    $rows[] = [
                        'id' => $sub1['id'],
                        'pid' => $sub1['pid'],
                        'icon' => $sub1['icon'],
                        'name' => $sub1['name'],
                        'created_at' => Carbon::now(),
                        'updated_at' => Carbon::now(),
                    ];
                }
            }
        }
        dd(GoodsCate::insert($rows));



        dd($service->sendSms('18181366398',SmsService::REG_CODE,['code' => '小兰']));



        for ($i = 1;$i < 100;$i++){
            $array[] = [
                'title' => '赠送'.$i,
                'user_id' => 69,
                'amount' => $i,
                'created_at' => Carbon::now(),
                'updated_at' => Carbon::now(),
            ];
        }

        MoneyDetail::insert($array);
    }


    /**
     * 解密
     */
    public function decode(DecodeRequest $request)
    {
        $aesKey    = base64_decode($request->sessionKey);
        $aesIV     = base64_decode($request->iv);
        $aesCipher = base64_decode($request->encryptedData);

        $result = openssl_decrypt( $aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);

        $dataObj = json_decode( $result );
        if( $dataObj  == NULL )
        {
            return error('解密失败1');
        }
//        if( $dataObj->watermark->appid != \config('app.app_id') )
//        {
//            return error('解密失败');
//        }
        return success($dataObj);

    }

    /**
     * 获取上传token
     * @return mixed
     */
    public function getUploadToken()
    {
        $disk = Storage::disk('qiniu');

        return success([
            'token' =>$disk->uploadToken(),
            'url'   => $disk->downloadUrl(),
        ]);
    }

    public function upload(Request $request)
    {
        $urls = [];

        foreach ($request->file() as $file) {
            $urls[] = Storage::url($file->store('images'));
        }

        return success([
            'urls' => $urls,
        ]);
    }


    /**
     * 获取open_id
     */
    public function getOpenId(Request $request)
    {
        $app_id = \config('app.app_id');
        $secret = \config('app.app_secret');
        $code = $request->code;
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=$app_id&secret=$secret&js_code=$code&grant_type=authorization_code";
//        dd($url);
        $result = curl_get($url);
        if ($result['session_key']){
//            $config = [
//                'app_id' => \config('app.app_id'),
//                'secret' => \config('app.app_secret'),
//
//                // 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
//                'response_type' => 'array',
//
//                //...
//            ];
//
//            $app = Factory::officialAccount($config);
//
//            $user = $app->user->get($result['open_id']);
//
//            $data['user'] = $user;
//            $data['open_id'] = $result['open_id'];
//            $data['session_key'] = $result['session_key'];
            return success($result);
        }

        return error($result['errmsg']);

    }


    public function tess()
    {
        $config = [
            'app_id' => \config('app.app_id'),
            'secret' => \config('app.app_secret'),

            // 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
            'response_type' => 'array',

            //...
        ];

        try{
            $app = Factory::officialAccount($config);

            $open_id = 'os5Na5Fhl19HJt7URbq1MiNS9yz4';
            $user = $app->user->get($open_id);
        }catch (\Exception $exception){
//            return error(700,$exception->getMessage());
        }
        try{
            $app = Factory::miniProgram($config);

            $open_id = 'os5Na5Fhl19HJt7URbq1MiNS9yz4';
            $user2 = $app->user->get($open_id);
        }catch (\Exception $exception){
//            return error(300,$exception->getMessage());
        }
        dd($user,$user2);

    }























}
